package com.example.designer.ChainOfResponsibility.servlet.filter;

import com.example.designer.ChainOfResponsibility.servlet.Request;
import com.example.designer.ChainOfResponsibility.servlet.Response;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhaoyunlong
 * @date 2020/12/17
 * @description
 */
public class UpgradeFilterChain implements Filter {

    List<Filter> filters = new ArrayList<>();

    /**
     * 链式 编程
     *
     * @param filter
     * @return
     */
    public UpgradeFilterChain add(Filter filter) {
        if (ObjectUtils.isEmpty(filter)) {
            throw new RuntimeException("filter is empty");
        }
        filters.add(filter);
        return this;
    }

    @Override
    public boolean doFilter(Request request, Response response) {
        for (Filter filter : filters) {
            boolean b = filter.doFilter(request, response);
            if (!b) {
                return false;
            }
        }
        return true;
    }
}
